package com.sinosun.autotestmachine.tools.proxy;

import org.json.JSONException;
import org.json.JSONObject;

import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.ValueInfo;
import com.sinosun.autotestmachine.tools.ValueType;
import com.sinosun.autotestmachine.tools.Collector.BaseCollector;
import com.sinosun.autotestmachine.tools.parser.ContentMaker;
import com.sinosun.autotestmachine.tools.parser.ParamKey;
import com.sinosun.autotestmachine.tools.proxy.callback.CallbackWrapper;
import com.sinosun.autotestmachine.tools.utils.SignDataFunc;
import com.sinosun.autotestmachine.tools.utils.Utils;
import com.sinosun.mstplib.Constants;
import com.sinosun.mstplib.LoginInfo;
import com.sinosun.mstplib.LogoutResultCallback;
import com.sinosun.mstplib.MstpClient;
import com.sinosun.mstplib.MstpException;
import com.sinosun.mstplib.UserInfo;

import android.text.TextUtils;
import android.util.Log;

public class LoginModule {
	protected static int sycnLogin(ProxyWrapper pw, MstpClient mstpClient, String paramJson) {
		String param = null;
		try {
			JSONObject jo = new JSONObject(paramJson);
			if (jo.has(ParamKey.MSTPID)) {
				param = jo.getString(ParamKey.MSTPID);
			} else {
				param = paramJson;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			param = paramJson;
		}
		
		if (TextUtils.isEmpty(param)) {
			return ErrorCode.ERR_PARAM_ERROR;
		}
		ValueInfo value = Utils.getUserRealInfo(param);
		String mstpId = value.getValueContent();
		if (value.getValueType() == ValueType.INDEX) {		// value 数据内容符合匹配规则，从内存中取出对应的 mstpId
			mstpId = App.getTestConfig().getUsers().get(value.getValueContent());
			if (TextUtils.isEmpty(mstpId)) {
				return ErrorCode.ERR_PARAM_ERROR;
			}
		}
		
		if (TextUtils.isEmpty(mstpId)) {
			return com.sinosun.mstplib.ErrorCode.ERR_PARAM_ERROR;
		}
		
        UserInfo userInfo = new UserInfo(App.getTestConfig().getAppId(), mstpId);
        userInfo.setAsymSafeMode(App.getTestConfig().getEncrption());
        mstpClient = MstpClient.getInstance(App.getInstance().getApplicationContext(), userInfo);
        mstpClient.setConfig(Constants.CONFIG_MSTP_HOST, App.getTestConfig().getServerIp()); 	//配置server
        mstpClient.setConfig(Constants.CONFIG_MSTP_PORT, App.getTestConfig().getPort());	//配置端口
        mstpClient.setConfig(Constants.MSTP_CONFIG_WEB_REQUEST_IS_CARRY_USER_IDENTIFIER_INFO, "0");
        pw.setMstpClient(mstpClient);

        LoginInfo loginInfo = new LoginInfo();
        long now = Utils.getWebsiteDatetime();
        long expireTime = now + 100000000;	//超时时间
        loginInfo.setExpireTime(expireTime);
        loginInfo.setCreationTime(now);
        loginInfo.setServerSignature(SignDataFunc.getAuthInfo(mstpId, expireTime, now, App.getTestConfig().getEncrption()));
        try {
            BaseCollector collector = new BaseCollector();
            CallbackWrapper.makeConnectionListener(mstpClient, collector);
            int loginRet = mstpClient.login(loginInfo);
        	if (loginRet == com.sinosun.mstplib.ErrorCode.ERR_STATE_LOGINED) {
        		mstpClient.getCloudDiskManager().createAccount();
        		return ErrorCode.SUCCESS;
        	}
        	collector.setResult(ErrorCode.ERR_TIMEOUT_ERROR);
        	collector.waitResult(120);
            return collector.getResult();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		} catch (MstpException e) {
			return e.getErrorCode();
		}
	}
	
	protected static int sycnLogout(MstpClient mstpClient) {
		Log.e("XXX", "sycnLogout with mstpId > " + mstpClient.getMstpId());
		ContentMaker.delAllFile(App.getInstance().getUploadPath());
		ContentMaker.delAllFile(App.getInstance().getDownloadPath());
		try {
			final BaseCollector collector = new BaseCollector();
			LogoutResultCallback logoutCallback = new LogoutResultCallback () {
				@Override public void onLogoutResult(int arg0) {
					collector.setResult(arg0);
					collector.countDown();
				}
			};
			mstpClient.logout(30, logoutCallback);
			collector.waitResult();
			if (collector.getResult() == com.sinosun.mstplib.ErrorCode.ERR_STATE_LOGOUTED || collector.getResult() == com.sinosun.mstplib.ErrorCode.ERR_REQUEST_TIMEOUT) {
				return ErrorCode.SUCCESS;
			}
			return collector.getResult();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return ErrorCode.ERR_UNEXPECT_RESULT;
		}
	}
}
